Catalyst / admin/Strike 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Strike

public

Web-Based UK Cyber Compliance Tool with Reporting

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Strike / StrikeXi v3 / backend / app / pdf_report.py 18576 B · main
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"""
PDF reporting engine for StrikeXi v3.

Renders a professional maturity report (HTML/CSS -> PDF via WeasyPrint) for
ANY framework (NCSC CAF, UK Cyber Security & Resilience Bill, ...). Objective
labels/titles are derived from the assessed framework rather than hard-coded.

v3 additions:
  * Score-comparison section (original vs latest revision) when an assessment
    has been re-scored, so previous and new maturity are both reported.
  * Evidence & Notes log (timestamped, with the acting username).

Charts are inline SVG (donut for overall, bars for per-objective) so they
embed cleanly in the PDF without an external rendering service.
"""
import math
import os
from datetime import date

from jinja2 import Template
from weasyprint import HTML
from sqlalchemy.orm import Session

from . import models, risk as risk_engine

REPORTS_DIR = "/app/reports"


def _short(oid: str) -> str:
    """Short objective code for compact labels: 'CSRB-A' -> 'A', 'A' -> 'A'."""
    return (oid or "").split("-")[-1]


def _band(score: float) -> str:
    if score >= 80:
        return "Strong"
    if score >= 60:
        return "Established"
    if score >= 40:
        return "Developing"
    return "Initial"


def _donut_svg(score: float) -> str:
    r, cx, cy = 52, 70, 70
    circ = 2 * math.pi * r
    pct = max(0.0, min(100.0, score)) / 100.0
    dash = circ * pct
    colour = "#2ecc71" if score >= 60 else ("#f39c12" if score >= 40 else "#e74c3c")
    return f"""
    <svg width="140" height="140" viewBox="0 0 140 140">
      <circle cx="{cx}" cy="{cy}" r="{r}" fill="none" stroke="#e8edf3" stroke-width="14"/>
      <circle cx="{cx}" cy="{cy}" r="{r}" fill="none" stroke="{colour}" stroke-width="14"
              stroke-dasharray="{dash:.2f} {circ:.2f}" stroke-linecap="round"
              transform="rotate(-90 {cx} {cy})"/>
      <text x="{cx}" y="{cy+2}" text-anchor="middle" font-size="26"
            font-family="DejaVu Sans" font-weight="bold" fill="#1f2d3d">{score:.0f}</text>
      <text x="{cx}" y="{cy+20}" text-anchor="middle" font-size="11"
            font-family="DejaVu Sans" fill="#7b8a9a">/ 100</text>
    </svg>"""


def _bars_svg(objective_scores: dict, obj_order: list) -> str:
    """Per-objective bar chart, driven by the framework's own objective order."""
    n = max(1, len(obj_order))
    total_w = 520
    gap = 24
    width = max(36, min(70, (total_w - 60 - gap * (n - 1)) / n))
    x = 40
    base_y = 180
    max_h = 140
    bars = ""
    for oid in obj_order:
        score = objective_scores.get(oid, 0.0)
        h = (score / 100.0) * max_h
        y = base_y - h
        colour = "#2ecc71" if score >= 60 else ("#f39c12" if score >= 40 else "#e74c3c")
        bars += f"""
          <rect x="{x:.1f}" y="{y:.1f}" width="{width:.1f}" height="{h:.1f}" rx="4" fill="{colour}"/>
          <text x="{x + width/2:.1f}" y="{y-6:.1f}" text-anchor="middle" font-size="12"
                font-family="DejaVu Sans" font-weight="bold" fill="#1f2d3d">{score:.0f}</text>
          <text x="{x + width/2:.1f}" y="{base_y+18}" text-anchor="middle" font-size="12"
                font-family="DejaVu Sans" fill="#1f2d3d">Obj {_short(oid)}</text>
        """
        x += width + gap
    return f"""
    <svg width="{total_w}" height="210" viewBox="0 0 {total_w} 210">
      <line x1="30" y1="180" x2="{total_w-20}" y2="180" stroke="#cdd6e0" stroke-width="1"/>
      {bars}
    </svg>"""


_TEMPLATE = Template(r"""
<!DOCTYPE html>
<html><head><meta charset="utf-8"><style>
  @page { size: A4; margin: 1.6cm 1.5cm; @bottom-center {
      content: "StrikeXi Maturity Report  —  Confidential  —  Page " counter(page) " of " counter(pages);
      font-size: 9px; color: #8a97a6; } }
  body { font-family: "DejaVu Sans", sans-serif; color: #2c3e50; font-size: 12px; }
  .cover { text-align:center; margin-top: 60px; }
  .brand { font-size: 34px; font-weight: bold; color: #16324f; letter-spacing: 1px; }
  .brand span { color: #2e86de; }
  .subtitle { font-size: 16px; color: #5b6b7b; margin-top: 6px; }
  .meta { margin-top: 50px; font-size: 14px; }
  .meta b { color:#16324f; }
  h2 { color:#16324f; border-bottom: 2px solid #2e86de; padding-bottom: 4px; margin-top: 28px; }
  .scorecard { display:flex; align-items:center; gap:24px; margin: 16px 0; }
  .band { display:inline-block; padding:4px 12px; border-radius:14px; color:#fff; font-weight:bold; }
  table { width:100%; border-collapse: collapse; margin-top:10px; }
  th, td { text-align:left; padding:8px 10px; border-bottom:1px solid #e3e9ef; font-size:11.5px; }
  th { background:#16324f; color:#fff; }
  .step { border-left:4px solid #2e86de; background:#f6f9fc; padding:10px 14px; margin:10px 0; }
  .step .num { font-weight:bold; color:#2e86de; }
  .pill { font-size:10px; padding:2px 8px; border-radius:10px; background:#eef3f8; color:#16324f; }
  .up { color:#1e8449; font-weight:bold; }
  .down { color:#c0392b; font-weight:bold; }
  .flat { color:#7b8a9a; }
  .page-break { page-break-before: always; }
</style></head><body>

  <div class="cover">
    <div class="brand">Strike<span>Xi</span></div>
    <div class="subtitle">{{ framework_name }} — Maturity Report</div>
    <div class="meta">
      <p><b>Organisation Assessed:</b> {{ org }}</p>
      <p><b>Framework:</b> {{ framework_name }}{% if framework_version %} ({{ framework_version }}){% endif %}</p>
      <p><b>Date of Assessment:</b> {{ adate }}</p>
      <p><b>Report Generated:</b> {{ generated }}</p>
      {% if comparison %}<p><b>Revisions:</b> {{ comparison.last_no }} (re-scored — original retained)</p>{% endif %}
    </div>
  </div>

  <div class="page-break"></div>
  <h2>Overall Maturity</h2>
  <div class="scorecard">
    {{ donut|safe }}
    <div>
      <p style="font-size:18px;"><b>Overall score: {{ overall }}/100</b></p>
      <p>Maturity band: <span class="band" style="background:{{ band_colour }}">{{ band }}</span></p>
      <p style="max-width:340px; color:#5b6b7b;">This score is the weighted mean of the
      {{ n_obj }} {{ framework_name }} objectives, derived from weighted answers across the
      assessed principles.</p>
    </div>
  </div>

  {% if comparison %}
  <h2>Re-assessment — Previous vs Latest</h2>
  <p style="color:#5b6b7b;">This assessment has been re-scored. The original result is retained
  for the audit trail; the table below compares the original and the latest maturity scores.</p>
  <div class="scorecard">
    <div style="text-align:center;">
      <div style="font-size:13px;color:#7b8a9a;">Original (rev {{ comparison.first_no }})</div>
      <div style="font-size:26px;font-weight:bold;color:#16324f;">{{ '%.0f'|format(comparison.first_overall) }}</div>
      <div style="font-size:10px;color:#9aa7b5;">{{ comparison.first_at }}</div>
    </div>
    <div style="font-size:22px;color:#7b8a9a;">&rarr;</div>
    <div style="text-align:center;">
      <div style="font-size:13px;color:#7b8a9a;">Latest (rev {{ comparison.last_no }})</div>
      <div style="font-size:26px;font-weight:bold;color:#16324f;">{{ '%.0f'|format(comparison.last_overall) }}</div>
      <div style="font-size:10px;color:#9aa7b5;">{{ comparison.last_at }}</div>
    </div>
    <div style="text-align:center;">
      <div style="font-size:13px;color:#7b8a9a;">Change</div>
      <div class="{{ 'up' if comparison.overall_delta > 0 else ('down' if comparison.overall_delta < 0 else 'flat') }}" style="font-size:26px;">
        {{ '%+.0f'|format(comparison.overall_delta) }}</div>
    </div>
  </div>
  <table>
    <tr><th>Objective</th><th>Title</th><th>Original</th><th>Latest</th><th>Change</th></tr>
    {% for r in comparison.rows %}
    <tr><td><b>{{ r.short }}</b></td><td>{{ r.title }}</td>
        <td>{{ r.prev_str }}</td><td>{{ r.cur_str }}</td>
        <td class="{{ 'up' if r.delta > 0 else ('down' if r.delta < 0 else 'flat') }}">{{ r.delta_str }}</td></tr>
    {% endfor %}
  </table>
  {% endif %}

  <h2>Per-Objective Scores</h2>
  {{ bars|safe }}
  <table>
    <tr><th>Objective</th><th>Title</th><th>Score</th><th>Band</th></tr>
    {% for oid, score in objective_rows %}
    <tr><td><b>{{ short(oid) }}</b></td><td>{{ obj_titles[oid] }}</td><td>{{ '%.0f'|format(score) }}/100</td>
        <td>{{ band_of(score) }}</td></tr>
    {% endfor %}
  </table>

  <h2>Risk Assessment Summary</h2>
  <p style="color:#5b6b7b;">This risk assessment is derived from the responses given in this
  assessment. Lower maturity indicates higher residual cyber risk.</p>
  <div class="scorecard">
    <div style="text-align:center;">
      <div class="band" style="background:{{ risk.overall_colour }};font-size:18px;padding:8px 20px;">{{ risk.overall_risk }} RISK</div>
      <div style="font-size:11px;color:#7b8a9a;margin-top:6px;">Overall residual risk</div>
    </div>
    <div style="max-width:380px;color:#41536b;">{{ risk.narrative }}</div>
  </div>
  <table>
    <tr><th>Risk band</th><th>Critical</th><th>High</th><th>Medium</th><th>Low</th></tr>
    <tr><td><b>Principles</b></td>
        <td>{{ risk.counts.Critical }}</td><td>{{ risk.counts.High }}</td>
        <td>{{ risk.counts.Medium }}</td><td>{{ risk.counts.Low }}</td></tr>
  </table>
  <table>
    <tr><th>Objective</th><th>Title</th><th>Score</th><th>Risk level</th></tr>
    {% for o in risk.objective_risks %}
    <tr><td><b>{{ short(o.objective_id) }}</b></td><td>{{ o.title }}</td>
        <td>{{ '%.0f'|format(o.score) }}/100</td>
        <td><span class="pill" style="background:{{ o.colour }};color:#fff;">{{ o.risk_level }}</span></td></tr>
    {% endfor %}
  </table>
  <h3 style="color:#16324f;margin-top:18px;">Key Risk Areas</h3>
  <p style="color:#5b6b7b;">The principles carrying the highest residual risk, in priority order.</p>
  <table>
    <tr><th>#</th><th>Objective</th><th>Principle</th><th>Score</th><th>Risk level</th></tr>
    {% for k in risk.key_risks %}
    <tr><td>{{ loop.index }}</td><td>{{ short(k.objective_id) }}</td>
        <td><b>{{ k.principle_id }}</b> — {{ k.principle_title }}</td>
        <td>{{ '%.0f'|format(k.score) }}/100</td>
        <td><span class="pill" style="background:{{ k.colour }};color:#fff;">{{ k.risk_level }}</span></td></tr>
    {% endfor %}
  </table>

  <div class="page-break"></div>
  <h2>Assessment Summary &amp; Breakdown</h2>
  <p style="color:#5b6b7b;">Score for every assessed principle, grouped by objective.
  Principles below the maturity threshold (70/100) trigger a remediation in the roadmap.</p>
  <table>
    <tr><th>Objective</th><th>Principle</th><th>Score</th><th>Status</th></tr>
    {% for oid, pid, pname, pscore in principle_rows %}
    <tr><td>{{ short(oid) }}</td><td><b>{{ pid }}</b> — {{ pname }}</td><td>{{ '%.0f'|format(pscore) }}/100</td>
        <td>{% if pscore < 70 %}<span class="pill" style="background:#fdecea;color:#c0392b;">Needs improvement</span>
            {% else %}<span class="pill" style="background:#eafaf1;color:#1e8449;">On track</span>{% endif %}</td></tr>
    {% endfor %}
  </table>

  <div class="page-break"></div>
  <h2>Actionable Maturity Roadmap</h2>
  <p style="color:#5b6b7b;">The following corrective actions were triggered by principles scoring
  below the maturity threshold. They are ordered by priority to form a step-by-step roadmap.</p>
  {% if roadmap %}
    {% for item in roadmap %}
    <div class="step">
      <p><span class="num">Step {{ loop.index }}.</span> <b>{{ item.title }}</b></p>
      <p style="margin:4px 0 6px;">
         <span class="pill">Objective {{ short(item.objective_id) }}</span>
         <span class="pill">Principle {{ item.principle_id }} — {{ item.principle_title }}</span>
         <span class="pill">Current score: {{ '%.0f'|format(item.principle_score) }}/100</span>
         <span class="pill">Effort: {{ item.effort }}</span>
         <span class="pill">Priority: {{ item.priority }}</span></p>
      <p style="margin:4px 0 0;"><b>Mitigation:</b> {{ item.detail }}</p>
    </div>
    {% endfor %}
  {% else %}
    <p><b>No remediation actions triggered.</b> All assessed principles met the maturity threshold.</p>
  {% endif %}

  {% if evidence %}
  <div class="page-break"></div>
  <h2>Evidence &amp; Notes</h2>
  <p style="color:#5b6b7b;">Evidence and notes recorded against this assessment. Each entry is
  date/time-stamped with the user who added it and is captured in the audit log.</p>
  <table>
    <tr><th>Date / time</th><th>User</th><th>Scope</th><th>Type</th><th>Detail</th></tr>
    {% for e in evidence %}
    <tr><td>{{ e.ts }}</td><td>{{ e.user }}</td><td>{{ e.scope }}</td>
        <td>{{ e.kind }}</td><td>{{ e.detail }}</td></tr>
    {% endfor %}
  </table>
  {% endif %}

</body></html>
""")


def generate_report(db: Session, assessment: models.Assessment) -> str:
    framework = db.query(models.Framework).filter(
        models.Framework.id == assessment.framework_id).first()
    framework_name = framework.name if framework else "Cyber Maturity"
    framework_version = framework.version if framework else None

    # Framework objective order + titles (v3: not hard-coded to CAF A-D).
    fobjs = (
        db.query(models.CafObjective)
        .filter(models.CafObjective.framework_id == assessment.framework_id)
        .order_by(models.CafObjective.sort_order).all()
    )
    obj_titles = {o.id: o.title for o in fobjs}
    obj_order = [o.id for o in fobjs]

    obj_scores = {
        s.objective_id: float(s.score)
        for s in db.query(models.AssessmentObjectiveScore)
        .filter(models.AssessmentObjectiveScore.assessment_id == assessment.id).all()
    }

    principles = {p.id: p for p in db.query(models.CafPrinciple).all()}
    sugg = {s.id: s for s in db.query(models.RemediationSuggestion).all()}

    actions = (
        db.query(models.RemediationAction)
        .filter(models.RemediationAction.assessment_id == assessment.id).all()
    )
    roadmap = []
    for a in actions:
        s = sugg.get(a.remediation_id)
        if not s:
            continue
        pr = principles.get(a.principle_id)
        roadmap.append({
            "title": s.title, "detail": s.detail, "effort": s.effort,
            "priority": s.priority, "principle_id": a.principle_id,
            "principle_title": pr.title if pr else "",
            "objective_id": pr.objective_id if pr else "",
            "principle_score": float(a.principle_score),
        })
    roadmap.sort(key=lambda x: (x["priority"], x["principle_score"]))

    # FULL per-principle breakdown (every assessed principle), grouped by objective
    pscores = (
        db.query(models.AssessmentPrincipleScore)
        .filter(models.AssessmentPrincipleScore.assessment_id == assessment.id).all()
    )
    principle_rows = []
    for ps in pscores:
        pr = principles.get(ps.principle_id)
        principle_rows.append((
            pr.objective_id if pr else "",
            ps.principle_id,
            pr.title if pr else "",
            float(ps.score),
        ))
    principle_rows.sort(key=lambda x: (x[0], x[1]))

    risk_summary = risk_engine.build_risk_summary(db, assessment)

    # ---- Revision comparison (original vs latest) ----
    revisions = (
        db.query(models.AssessmentRevision)
        .filter(models.AssessmentRevision.assessment_id == assessment.id)
        .order_by(models.AssessmentRevision.revision_no).all()
    )
    comparison = None
    if len(revisions) > 1:
        first, last = revisions[0], revisions[-1]
        f_obj = (first.snapshot or {}).get("objective_scores", {})
        l_obj = (last.snapshot or {}).get("objective_scores", {})
        rows = []
        for oid in obj_order:
            prev = f_obj.get(oid)
            cur = l_obj.get(oid)
            delta = (cur or 0) - (prev or 0)
            rows.append({
                "short": _short(oid), "title": obj_titles.get(oid, ""),
                "prev_str": "—" if prev is None else f"{prev:.0f}/100",
                "cur_str": "—" if cur is None else f"{cur:.0f}/100",
                "delta": delta,
                "delta_str": "—" if (prev is None or cur is None) else f"{delta:+.0f}",
            })
        comparison = {
            "first_no": first.revision_no,
            "first_overall": float(first.overall_score or 0),
            "first_at": first.created_at.strftime("%d %b %Y %H:%M"),
            "last_no": last.revision_no,
            "last_overall": float(last.overall_score or 0),
            "last_at": last.created_at.strftime("%d %b %Y %H:%M"),
            "overall_delta": float(last.overall_score or 0) - float(first.overall_score or 0),
            "rows": rows,
        }

    # ---- Evidence & notes log ----
    q_codes = {q.id: q.code for q in db.query(models.Question).all()}
    ev_rows = (
        db.query(models.AssessmentEvidence)
        .filter(models.AssessmentEvidence.assessment_id == assessment.id)
        .order_by(models.AssessmentEvidence.created_at).all()
    )
    evidence = []
    for e in ev_rows:
        scope = q_codes.get(e.question_id, "Question") if e.question_id else "Assessment-wide"
        if e.kind == "evidence":
            detail = f"File: {e.file_name}" + (f" — {e.content}" if e.content else "")
        else:
            detail = e.content or ""
        evidence.append({
            "ts": e.created_at.strftime("%d %b %Y %H:%M"),
            "user": e.created_by, "scope": scope,
            "kind": "Evidence file" if e.kind == "evidence" else "Note",
            "detail": detail,
        })

    overall = float(assessment.overall_score or 0.0)
    band = _band(overall)
    band_colour = "#27ae60" if overall >= 60 else ("#f39c12" if overall >= 40 else "#e74c3c")

    html = _TEMPLATE.render(
        org=assessment.organisation_name,
        framework_name=framework_name,
        framework_version=framework_version,
        adate=assessment.assessment_date.strftime("%d %B %Y"),
        generated=date.today().strftime("%d %B %Y"),
        donut=_donut_svg(overall),
        bars=_bars_svg(obj_scores, obj_order),
        overall=f"{overall:.0f}",
        band=band, band_colour=band_colour,
        n_obj=len(obj_order),
        obj_titles=obj_titles,
        objective_rows=[(oid, obj_scores[oid]) for oid in obj_order if oid in obj_scores],
        principle_rows=principle_rows,
        roadmap=roadmap,
        risk=risk_summary,
        comparison=comparison,
        evidence=evidence,
        band_of=_band,
        short=_short,
    )

    os.makedirs(REPORTS_DIR, exist_ok=True)
    out_path = os.path.join(REPORTS_DIR, f"StrikeXi_Report_{assessment.id}.pdf")
    HTML(string=html).write_pdf(out_path)
    return out_path